const express = require('express');
const axios = require('axios');
const router = express.Router();

let code = ''

router.get('/', async (req, res) => {
    code = req.query.code

    const { data: gettokenResult } = await axios.get('https://qyapi.weixin.qq.com/cgi-bin/gettoken', {
        params: {
            corpid: 'wwbfa1c579e5d4cab9',
            // 有票lite
            corpsecret: 'bF_x3g4cF7FW2PNDjP7o9ZsItDF3sOS2y2Czd59surA'
        },
    });

    console.log('sssssssssss', gettokenResult)
    const { errcode, access_token } = gettokenResult
    if (errcode === 0) {
        // 获取用户userid等信息
        const sessionResult = await jscode2session(access_token)
        delete sessionResult.session_key
        return res.json({ ...sessionResult, access_token });
    }

    return res.json(gettokenResult)
})

const jscode2session = async (token) => {
    const { data } = await axios.get(`https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token=${token}&js_code=${code}&grant_type=authorization_code`);
    console.log('ssaa', data)
    return Promise.resolve(data)
}

module.exports = router